package com.ita.tba.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.ita.tba.dao.OrderListDao;
import com.ita.tba.po.OrderList;
import com.ita.tba.util.DbUtil;
import com.ita.tba.util.DidNumUtil;

public class OrderListDaoImpl implements OrderListDao{

	@Override
	public int insertOrderList(OrderList orderList) {
		String sql = "insert into tbaorderlist(userid,total,didnum,orderdate,orderid) values (?,?,?,?,tbaorder_seq.nextval)";
		
		Connection con = null;
		PreparedStatement pst = null;
		con = DbUtil.connect();
		String didNumStr = DidNumUtil.didNumMapToStr(orderList.getDidNum());
		 
		int m = 0;
		try {
			pst = con.prepareStatement(sql);
			con.setAutoCommit(false);	
			pst.setInt(1, orderList.getUid());
			pst.setDouble(2, orderList.getTotalPrice());
			pst.setString(3, didNumStr);
			pst.setString(4, orderList.getTime());
			m = pst.executeUpdate();
			con.commit();
		} catch (SQLException e) {
			try {
				con.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}finally {
			DbUtil.free(con, pst, null);
		}
		return m;
	}

	@Override
	public List<OrderList> selectOrderList(int uid) {
		List<OrderList> list = new ArrayList<OrderList>();
		String sql = "select * from tbaorderlist where userid=? order by orderid";

		Connection con = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		con = DbUtil.connect();

		try {
			pst = con.prepareStatement(sql);
			pst.setInt(1, uid);
			rs = pst.executeQuery();
			
			while (rs.next()) {
				OrderList o = new OrderList();
				o.setUid(uid);
				o.setOid(rs.getInt("orderid"));
				o.setTotalPrice(rs.getDouble("total"));
				Map<Integer, Integer> didNumMap = DidNumUtil.didNumStrToMap(rs.getString("didnum"));
				o.setDidNum(didNumMap);
				o.setTime(rs.getString("orderdate"));
				list.add(o);
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DbUtil.free(con, pst, rs);
		}
		return list;
	}

}
